package site.immonkey.mailtest.utils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class TLSUtils {
	private static final SSLContext SSL_CONTEXT;
	private static final SSLSocketFactory SSL_SOCKET_FACTORY;

	static {
		try {
			X509TrustManager trustManager = new X509TrustManager() {
				@Override
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

				@Override
				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			SSL_CONTEXT = SSLContext.getInstance("TLS");
			SSL_CONTEXT.init(null, new TrustManager[] { trustManager }, null);
			SSL_SOCKET_FACTORY = SSL_CONTEXT.getSocketFactory();
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	public static SSLSocket ssl(Socket socket, InetSocketAddress target) throws IOException {
		return (SSLSocket) SSL_SOCKET_FACTORY.createSocket(socket, target.getHostName(), target.getPort(), true);
	}

	public static SSLSocket create(String host, int port) throws IOException {
		return (SSLSocket) SSL_SOCKET_FACTORY.createSocket(host, port);
	}
}
